#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<time.h>
#include<vector>
#include<string>
#include<unordered_map>
#include<sys/types.h>
#include<sys/wait.h>

using namespace std;

typedef void(*functor)();
vector<functor>functors;
unordered_map<int,string> info; 




void f1()
{
    cout<<"方法1"<<endl;
}

void f2()
{
    cout<<"方法2"<<endl;
}

void f3()
{
    cout<<"方法3"<<endl;
}

void LoadFunctors()
{
    functors.push_back(f1);
    info.insert({functors.size(),"方法1"});
    functors.push_back(f2);
    info.insert({functors.size(),"方法2"});
    functors.push_back(f3);
    info.insert({functors.size(),"方法3"});

    cout<<"方法集加载成功"<<endl;
}

int main()
{
    LoadFunctors();
    int pipefd[2]={0};
    if(pipe(pipefd)!=0)
    {
        cerr<<"pipe error"<<endl;
        return 1;
    }
    pid_t id=fork();
    if(id==0)
    {
        close(pipefd[1]);
        int tag=0;
        while(1)
        {
            int dia=read(pipefd[0],&tag,4);
            if(dia==4)
            {
                //执行方法
                if(tag<functors.size())
                {
                    cout<<"子进程执行方法: ";
                    functors[tag]();
                }
                else
                {
                    cout<<"error"<<endl;
                }
            }
            else if(dia==0)
            {
                //方法执行结束
                cout<<"方法执行结束"<<endl;
                break;
            }
            else
            {
                //读取失败
            }
        }
        close(pipefd[0]);
        exit(0);
    }
    else
    {
        close(pipefd[0]);
        srandom(time(nullptr));
        while(1)
        {
            int tag=random()%functors.size();
            write(pipefd[1],&tag,4);
            cout<<"父进程指派任务：编号："<<tag+1<<"任务为："<<info[tag+1]<<endl;
            sleep(2);
        }
    }
    

    return 0;
}
